package com.molyfun.parents.zhibo;

import android.Manifest;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.RectF;
import android.hardware.Camera;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.GsonBuilder;
import com.ksyun.mc.agoravrtc.KMCAuthResultListener;
import com.ksyun.mc.agoravrtc.stats.OnLogEventListener;
import com.ksyun.media.player.IMediaPlayer;
import com.ksyun.media.player.KSYMediaPlayer;
import com.ksyun.media.player.KSYTextureView;
import com.ksyun.media.streamer.capture.CameraCapture;
import com.ksyun.media.streamer.capture.camera.CameraTouchHelper;
import com.ksyun.media.streamer.encoder.VideoEncodeFormat;
import com.ksyun.media.streamer.kit.KSYStreamer;
import com.ksyun.media.streamer.kit.StreamerConstants;
import com.makeramen.roundedimageview.RoundedTransformationBuilder;
import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.common.BaseActivity;
import com.molyfun.parents.activity.common.HorizontalShareDialogActivity;
import com.molyfun.parents.fragment.dialog.CommonChooseDialogFragment;
import com.molyfun.parents.im.MyConnectionListener;
import com.molyfun.parents.im.MyTIMMsgListener;
import com.molyfun.parents.im.model.BaseMessageEntity;
import com.molyfun.parents.impl.NetWorkChangeCallback;
import com.molyfun.parents.rest.BaseResponse;
import com.molyfun.parents.rest.RestClient;
import com.molyfun.parents.rest.bean.ZhiboRoomResponse;
import com.molyfun.parents.utils.Const;
import com.molyfun.parents.utils.GsonUtil;
import com.molyfun.parents.utils.NetWorkUtil;
import com.molyfun.parents.utils.PreferencesStorageUtil;
import com.molyfun.parents.view.StrokeTextView;
import com.molyfun.parents.view.zhibo.ZhiboControlView;
import com.molyfun.parents.view.zhibo.ZhiboImListView;
import com.molyfun.parents.zhibo.im.ImModel;
import com.molyfun.parents.zhibo.im.ZhiboAddImMsgRequest;
import com.molyfun.parents.zhibo.im.event.EventExecuter;
import com.molyfun.parents.zhibo.im.event.EventHandler;
import com.molyfun.parents.zhibo.impl.IZhiboIns;
import com.molyfun.parents.zhibo.kit.KMCAgoraStreamer;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;
import com.tencent.imsdk.TIMConversation;
import com.tencent.imsdk.TIMManager;

import java.io.IOException;
import java.util.HashMap;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by kongweile on 29/10/2016.
 * Auto hide and show navigation bar and status bar for API >= 19.
 * Keep screen on.
 */

public class ZhiboBaseActivity<T> extends BaseActivity implements View.OnClickListener, IZhiboIns<T>, NetWorkChangeCallback, EventExecuter, MyTIMMsgListener.ITIMMsgReceivedCallback,
        ZhiboControlView.ZhiboControlViewShowCallback {

//    public String mZhiboRoomId;

    private static final String TAG = ZhiboBaseActivity.class.getSimpleName();

    private static final int MESSAGE_ID_RECONNECTING = 0x01;

    protected TIMConversation conversation;

    private final static int PERMISSION_REQUEST_CAMERA_AUDIOREC = 1;

    private boolean mIsLandscape;

    protected String subjectId;//用于分享

    protected String mZhiboIdCopy;

    @InjectView(R.id.player_view)
    KSYTextureView mPlayerView;
//    @InjectView(R.id.camera_preview)
//    GLSurfaceView mCameraPreviewView;
//    @InjectView(R.id.camera_hint)
//    CameraHintView mCameraHintView;
    @InjectView(R.id.zhibo_controller_view)
    ZhiboControlView zhiboControlView;
    @InjectView(R.id.game)
    WebView mGameView;
    @InjectView(R.id.zhibo_im_list_view)
    ZhiboImListView mZhiboImListView;
    //    @InjectView(R.id.material_container_layout)
//    LinearLayout mMaterialContainerLayout;
    @InjectView(R.id.header)
    ImageView mHeader;
    @InjectView(R.id.rtc_invite_layout)
    LinearLayout mInviteLayout;
    @InjectView(R.id.accept_rtc)
    ImageView mRtcAccept;
    @InjectView(R.id.refuse_rtc)
    ImageView mRtcRefuse;
    @InjectView(R.id.user_leave)
    TextView mUserLeave;
    @InjectView(R.id.teacher_name)
    StrokeTextView mTeacherName;

    @InjectView(R.id.ic_video_scale)
    ImageView mVideoScale;
    @InjectView(R.id.ic_webview_scale)
    ImageView mWebViewScale;


    @InjectView(R.id.large_layout_container)
    RelativeLayout mLargeLayoutContainer;
    @InjectView(R.id.top_layout)
    LinearLayout mTopLayout;
    @InjectView(R.id.web_view_container)
    FrameLayout mWebViewContainer;
    @InjectView(R.id.zhibo_container)
    FrameLayout mZhiboContainer;
//    @InjectView(R.id.container_layout)
//    ImageView mContainerLayout;

    private LinearLayout.LayoutParams webLayoutParams;
    private LinearLayout.LayoutParams zhiboLayoutParams;

    MyConnectionListener myConnectionListener;

//    protected ZhiboListResponse.ZhiboBean zhiboBean;


    protected static final String ZHIBO_BEAN = "zhibo_bean";

    private KMCAgoraStreamer mStreamer;

    private boolean mIsActivityPaused = false;
    private boolean mIsPublishStreamStarted = false;
    private boolean mIsCaling = false;
    private boolean mAutoStart = true;

    protected BaseStreamConfig mConfig;

//    protected GetSubjectResponse.SubjectDetailBean mSubjectDetailBean;

    protected String mZhiboId;

    protected String mZhiboname;

    //如果是小组直播，不展示分享
    protected boolean isClassRoom = false;

    protected String mZhiboTeacherName;
    protected int mZhiboUserCount;



    private HashMap<String, Integer> kv = new HashMap<>();

    @Override
    public void onZhiboControlViewVisibleChange(boolean isShow) {
        if(isShow){
            mVideoScale.setVisibility(View.VISIBLE);
            mWebViewScale.setVisibility(View.VISIBLE);
        }else{
            mVideoScale.setVisibility(View.GONE);
            mWebViewScale.setVisibility(View.GONE);
        }
    }

    @Override
    public void onMessage(BaseMessageEntity messageEntity) {
        switch (messageEntity.getEventtype()) {
            case MyTIMMsgListener.EventType.LIVE:
                EventHandler.handlerEvent(messageEntity, this);
                break;
        }
    }

    @Override
    public void onMessageNewStr(ImModel.ImStringModel imStringModel) {
        mZhiboImListView.addMsg(imStringModel);
    }

    @Override
    public void onMessageNewUser(ImModel.UserCountModel userCountBody) {
        mZhiboImListView.addMsg(userCountBody);
    }

    @Override
    public void onMessageUserOut(ImModel.UserCountModel userCountBody) {
        mZhiboImListView.addMsg(userCountBody);
    }

    @Override
    public void onMessageRtcCancel(ImModel.RtcInviteModel rtcInviteModel) {
        if (rtcInviteModel.getData().getTargetuserid().equals(MFPApplication.getInstance().getUser().getId())) {
            mInviteLayout.setVisibility(View.GONE);
            zhiboControlView.setRtcBegin(false);
        }
    }

    @Override
    public void onMessageRtcStop() {
        stopConference();
        zhiboControlView.setRtcBegin(false);
    }

    @Override
    public void showToast(String msg) {
        toast(msg);
    }

    @Override
    public void onMessageRtcConfim(ImModel.RtcInviteModel rtcInviteModel) {

    }

    @Override
    public void onRefreshStream() {
        if(mRoomBean != null){
            mPlayerView.stop();
            startToPlay(mRoomBean.getLivertmp(), false);
            mPlayerView.setComeBackFromShare(true);
        }
    }

    Transformation transformation = new RoundedTransformationBuilder()
            .borderColor(Color.TRANSPARENT)
            .borderWidthDp(6)
            .oval(false)
            .build();

    @Override
    public void onMessageRtcInvite(ImModel.RtcInviteModel rtcInviteModel) {
        mInviteLayout.setVisibility(View.VISIBLE);
        if (rtcInviteModel.getUser() != null) {
            if (!TextUtils.isEmpty(rtcInviteModel.getUser().getImageUrl())) {
                Picasso.with(ZhiboBaseActivity.this)
                        .load(rtcInviteModel.getUser().getImageUrl())
                        .transform(transformation)
                        .placeholder(R.mipmap.ic_rtc_invite_teacher_default)
                        .error(R.mipmap.ic_rtc_invite_teacher_default)
                        .into(mHeader);
            }
            mTeacherName.setText(rtcInviteModel.getUser().getUserName());
        }
        mRtcInviteModel = rtcInviteModel;
    }

    ImModel.RtcStartModel mRtcStartModel;

    @Override
    public void onMessageRtcStart(ImModel.RtcStartModel rtcStartModel) {

        mRtcStartModel = rtcStartModel;
        changeUserStateRtc(true);
        zhiboControlView.setRtcBegin(true);

//        startConference(rtcStartModel.getData().getChannel());
    }

    @Override
    public void onTeacherEnter() {
        mUserLeave.setVisibility(View.GONE);
        if (mPlayerView != null) {
            mPlayerView.prepareAsync();
        }
        Const.sZhiboStateCache.put(mZhiboIdCopy, "prog");
    }

    @Override
    public void onShare() {
        String shareUrl = "";

        switch (PreferencesStorageUtil.getServerMode(MFPApplication.getInstance())) {
            case PreferencesStorageUtil.ServerMode.OFFICAL:
                shareUrl = "http://h5.helloparents.elimautism.com/#/subject/detail/" + subjectId;
                break;
            case PreferencesStorageUtil.ServerMode.PREPARE:
                shareUrl = "http://h5.helloparentstest.elimautism.com/#/subject/detail/" + subjectId;
                break;
            case PreferencesStorageUtil.ServerMode.TEST:
                shareUrl = "http://192.168.3.30:8087/helloparents-client/#/subject/detail/  " + subjectId;
                break;
        }

        HorizontalShareDialogActivity.sharePage(ZhiboBaseActivity.this, "课程直播", "课程直播", shareUrl);
    }

    @Override
    public void onTeacherLeave() {
        if (mIsCaling) {
            stopConference();
            zhiboControlView.setRtcBegin(false);
        }
        mPlayerView.stop();
        mUserLeave.setVisibility(View.VISIBLE);
        toast("主播已离开房间");
        Const.sZhiboStateCache.put(mZhiboIdCopy, "init");
    }

    @Override
    public void onMessageGalleryOperate(final ImModel.GalleryBody galleryBody, int operateType) {
        System.out.println("galleryBody-->" + GsonUtil.toJson(galleryBody));
        System.out.println("onMessageGalleryOperate-operateType->" + operateType);
        switch (operateType) {
            case ImModel.GalleryOperateType.OperateTypeOpen:

                if (!galleryBody.getGtype().equals("4")) {

                    String url = "";
                    System.out.println("url--->" + url);


                    mGameView.loadUrl("javascript:loadMatter('" + galleryBody.getUrl() + "','" + galleryBody.getGtype() + "')");

                    mGameView.setWebViewClient(new WebViewClient() {

                        @Override
                        public void onPageStarted(WebView view, String url, Bitmap favicon) {
                            super.onPageStarted(view, url, favicon);
                        }

                        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                            handler.proceed();
                        }

                        @Override
                        public void onPageFinished(WebView view, String url) {
                            super.onPageFinished(view, url);
                            //2视频 3音频 4游戏
                            System.out.println("onPageFinished-->" + galleryBody.getGtype());
                            System.out.println("onPageFinished-js->" + "javascript:playTimeVideo(" + galleryBody.getTimepoint() + ")");
                            if (galleryBody.getGtype().equals("2") || galleryBody.getGtype().equals("3")) {
                                //                            mGameView.loadUrl("javascript:playTimeVideo(2)");
                                mGameView.loadUrl("javascript:playTimeVideo(" + galleryBody.getTimepoint() + ")");
                            } else if (galleryBody.getGtype().equals("3")) {
                                mGameView.loadUrl("javascript:playTimeAudio(" + galleryBody.getTimepoint() + ")");
                            }
                        }

                        @Override
                        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                            if (!url.equals("about:blank")) {
                            }
                            return false;
                        }
                    });

//                    mGameView.loadUrl(url);
                } else {
//                    mGameView.loadUrl(galleryBody.getUrl());
                }
                if ((TextUtils.isEmpty(mLastGalleryStr)) || (!TextUtils.isEmpty(mLastGalleryStr) && !mLastGalleryStr.equals(galleryBody.getUrl()))) {
                    mGameView.loadUrl("javascript:loadMatter('" + galleryBody.getUrl() + "','" + galleryBody.getGtype() + "')");
                    mLastGalleryStr = galleryBody.getUrl();
                }

                break;
            case ImModel.GalleryOperateType.OperateTypeClose:
                mGameView.loadUrl(RestClient.COMMON_GALLERY_BASE_URL);
                mLastGalleryStr = "";
                break;
            case ImModel.GalleryOperateType.OperateTypePause:
                if ((TextUtils.isEmpty(mLastGalleryStr)) || (!TextUtils.isEmpty(mLastGalleryStr) && !mLastGalleryStr.equals(galleryBody.getUrl()))) {
                    mGameView.loadUrl("javascript:loadMatter('" + galleryBody.getUrl() + "','" + galleryBody.getGtype() + "')");
                    mLastGalleryStr = galleryBody.getUrl();
                }
                if (galleryBody.getGtype().equals("2")) {
                    mGameView.loadUrl("javascript:pauseVideo()");
                } else if (galleryBody.getGtype().equals("3")) {
                    mGameView.loadUrl("javascript:pauseAudio()");
                }
                break;
            case ImModel.GalleryOperateType.OperateTypeSeek:
                if ((TextUtils.isEmpty(mLastGalleryStr)) || (!TextUtils.isEmpty(mLastGalleryStr) && !mLastGalleryStr.equals(galleryBody.getUrl()))) {
                    mGameView.loadUrl("javascript:loadMatter('" + galleryBody.getUrl() + "','" + galleryBody.getGtype() + "')");
                    mLastGalleryStr = galleryBody.getUrl();
                }
                System.out.println("OperateTypeSeek-js->" + "javascript:playTimeVideo(" + galleryBody.getTimepoint() + ")");
                if (galleryBody.getGtype().equals("2")) {
                    if (galleryBody.getTimepoint() == 0) {
                        mGameView.loadUrl("javascript:playVideo()");
                    } else {
                        mGameView.loadUrl("javascript:playTimeVideo(" + galleryBody.getTimepoint() + ")");
                    }
                } else if (galleryBody.getGtype().equals("3")) {
                    if (galleryBody.getTimepoint() == 0) {
                        mGameView.loadUrl("javascript:playAudio()");
                    } else {
                        mGameView.loadUrl("javascript:playTimeAudio(" + galleryBody.getTimepoint() + ")");
                    }
                }
                break;
        }
    }

    private String mLastGalleryStr = "";

    ImModel.RtcInviteModel mRtcInviteModel;

    public static interface AudienceState {
        int StateLook = 1001;
        int StateRtc = 1002;
    }

    public static class BaseStreamConfig {
        public String mUrl;
        public int mCameraFacing;
        public float mFrameRate;
        public int mVideoKBitrate;
        public int mAudioKBitrate;
        public int mTargetResolution;
        public int mOrientation;
        public int mEncodeMethod;
        public boolean mAutoStart;
        public boolean mShowDebugInfo;

        public BaseStreamConfig fromJson(String json) {
            return new GsonBuilder().create().fromJson(json, this.getClass());
        }

        public String toJson() {
            return new GsonBuilder().create().toJson(this);
        }
    }

    protected ZhiboRoomResponse.RoomBean mRoomBean;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zhibo);
        ButterKnife.inject(this);

        WebSettings webSettings = mGameView.getSettings();
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);              // 正常加载缓存
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(true);
        webSettings.setUseWideViewPort(true);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

//        AndroidBug5497Workaround.assistActivity(this);

        mGameView.setWebChromeClient(new WebChromeClient() {});

        mGameView.loadUrl(RestClient.COMMON_GALLERY_BASE_URL);

        //获取群聊会话
//        String groupId = "@TGS#3MHSAMAF5";  //获取与群组会话

        NetChangeReceiver.addNetCallback(this);

        mRtcAccept.setOnClickListener(this);
        mRtcRefuse.setOnClickListener(this);
        mWebViewScale.setOnClickListener(this);
        mVideoScale.setOnClickListener(this);

        webLayoutParams = (LinearLayout.LayoutParams) mWebViewContainer.getLayoutParams();
        zhiboLayoutParams = (LinearLayout.LayoutParams) mZhiboContainer.getLayoutParams();

        initRtc();

        myConnectionListener = new MyConnectionListener(this);
//        EMClient.getInstance().addConnectionListener(myConnectionListener);
        TIMManager.getInstance().getUserConfig().setUserStatusListener(myConnectionListener);
        mZhiboImListView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        break;
                    case MotionEvent.ACTION_UP:
                        zhiboControlView.changeBottomBarState();
                        return true;
                }
                return false;
            }
        });
        if(isClassRoom){
            zhiboControlView.setShareVisiable(false);
        }
//        if(!TextUtils.isEmpty(MFPApplication.getInstance().getUser().getWatermarkurl())){
//            Picasso.with(ZhiboBaseActivity.this)
//                    .load(MFPApplication.getInstance().getUser().getWatermarkurl())
//                    .into(mContainerLayout);
//        }
        zhiboControlView.setZhiboControlViewShowCallback(this);
    }

    protected void startToPlay(String url) {
        startToPlay(url, true);
    }

    protected void startToPlay(String url, boolean showProgress) {
        Log.i("buffer", "视频加载开始了");
        if(showProgress){
            showProgressDialog();
        }
        mPlayerView.setOnPreparedListener(mOnPreparedListener);
        mPlayerView.setOnErrorListener(mOnPlayerErrorListener);
        mPlayerView.setOnInfoListener(mOnPlayerInfoListener);
        mPlayerView.setOnCompletionListener(mOnCompletionListener);
        mPlayerView.setVolume(1.0f, 1.0f);
        mPlayerView.setBufferTimeMax(2);
//        }

//        if (bufferSize > 0) {
        mPlayerView.setBufferSize(15);
//        }
//        if (prepareTimeout > 0 && readTimeout > 0) {
        mPlayerView.setTimeout(5, 30);
        mPlayerView.setDecodeMode(KSYMediaPlayer.KSYDecodeMode.KSY_DECODE_MODE_AUTO);
//            }
//        }

        try {
            mPlayerView.setDataSource(url);
            mPlayerView.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //改变直播view展示
    public void changeUserStateRtc(boolean isRtc) {
        if (isRtc) {
//            mPlayerView.pause();
//            mPlayerView.setVisibility(View.GONE);
//            mCameraPreviewView.setVisibility(View.VISIBLE);
//            mCameraHintView.setVisibility(View.VISIBLE);

            if (!isConfig) {
                mConfig = getConfig();
                config();
            }

//            CameraTouchHelper cameraTouchHelper = new CameraTouchHelper();
//            cameraTouchHelper.setCameraCapture(mStreamer.getCameraCapture());
//            mCameraPreviewView.setOnTouchListener(cameraTouchHelper);
//            // set CameraHintView to show focus rect and zoom ratio
//            cameraTouchHelper.setCameraHintView(mCameraHintView);
//
//            //for rtc sub screen
//            cameraTouchHelper.addTouchListener(mSubScreenTouchListener);
//            mStreamer.setDisplayPreview(mCameraPreviewView);
//            mStreamer.onResume();
//            mCameraHintView.hideAll();
            startCameraPreviewWithPermCheck();


            if (mRtcStartModel != null) {
                startConference(mRtcStartModel.getData().getChannel());
            }
        } else {
//            mPlayerView.setVisibility(View.VISIBLE);
//            mCameraPreviewView.setVisibility(View.GONE);
//            mCameraHintView.setVisibility(View.GONE);
            mPlayerView.setComeBackFromShare(true);
            mPlayerView.start();
        }
    }


    private boolean isRtcInit = false;

    private void initRtc() {
        System.out.println("initRtc");
        if (isRtcInit) {
            return;
        }
        System.out.println("isRtcInit");
        isRtcInit = true;
        String token = "ad1e91ae9d758b71380e08a9e4199036";
        mStreamer = new KMCAgoraStreamer(this);
        mStreamer.setRotateDegrees(90);
        mStreamer.authorize(token, new KMCAuthResultListener() {
            @Override
            public void onSuccess() {
                toast("鉴权成功");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        changeUserStateRtc(true);
//                        startConference();
//                        mRtcRequest.setEnabled(true);
                    }
                });
            }

            @Override
            public void onFailure(int errCode) {
                toast("鉴权失败！  错误码: " + errCode);
            }
        });


        mStreamer.setRTCLogListener(new OnLogEventListener() {
            @Override
            public void onLogEvent(String s) {
                dismissProgressDialog();
            }
        });

    }


    private boolean isConfig = false;

    protected void config() {
        isConfig = true;
        // 设置推流URL地址
//        if (!TextUtils.isEmpty(mConfig.mUrl)) {
//            mStreamer.setUrl(mConfig.mUrl);
//        }

        // 设置推流分辨率
//        mStreamer.setPreviewResolution(mConfig.mTargetResolution);
//        mStreamer.setTargetResolution(mConfig.mTargetResolution);
        mStreamer.setPreviewResolution(640, 360);
        mStreamer.setTargetResolution(640, 360);

        // 设置编码方式（硬编、软编）
        mStreamer.setEncodeMethod(mConfig.mEncodeMethod);
        // 硬编模式下默认使用高性能模式(high profile)
        if (mConfig.mEncodeMethod == StreamerConstants.ENCODE_METHOD_HARDWARE) {
            mStreamer.setVideoEncodeProfile(VideoEncodeFormat.ENCODE_PROFILE_HIGH_PERFORMANCE);
        }

        // 设置推流帧率
        if (mConfig.mFrameRate > 0) {
            mStreamer.setPreviewFps(mConfig.mFrameRate);
            mStreamer.setTargetFps(mConfig.mFrameRate);
        }

        // 设置推流视频码率，三个参数分别为初始码率、最高码率、最低码率
        int videoBitrate = mConfig.mVideoKBitrate;
        if (videoBitrate > 0) {
            mStreamer.setVideoKBitrate(videoBitrate * 3 / 4, videoBitrate, videoBitrate / 4);
        }

        // 设置音频码率
        if (mConfig.mAudioKBitrate > 0) {
            mStreamer.setAudioKBitrate(mConfig.mAudioKBitrate);
        }

        // 设置视频方向（横屏、竖屏）
        if (mConfig.mOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            mIsLandscape = true;
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            mStreamer.setRotateDegrees(90);
        } else if (mConfig.mOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            mIsLandscape = false;
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            mStreamer.setRotateDegrees(0);
        }

        // 选择前后摄像头

        // 设置预览View

//        mStreamer.setDisplayPreview(mCameraPreviewView);
        mStreamer.setEnableRepeatLastFrame(false);  // disable repeat last frame in background
        mStreamer.setEnableAutoRestart(true, 3000); // enable auto restart
        mStreamer.setCameraFacing(CameraCapture.FACING_FRONT);
        mStreamer.setFrontCameraMirror(false);
        mStreamer.setMuteAudio(false);
        mStreamer.setEnableAudioPreview(false);

        // 设置回调处理函数
        mStreamer.setOnInfoListener(mOnInfoListener);
        mStreamer.setOnErrorListener(mOnErrorListener);
        // 禁用后台推流时重复最后一帧的逻辑（这里我们选择切后台使用背景图推流的方式）
        mStreamer.setEnableRepeatLastFrame(false);
    }

    protected void onStreamerError(int what, int msg1, int msg2) {
        Log.e(TAG, "streaming error: what=" + what + " msg1=" + msg1 + " msg2=" + msg2);
        switch (what) {
            case StreamerConstants.KSY_STREAMER_AUDIO_RECORDER_ERROR_START_FAILED:
            case StreamerConstants.KSY_STREAMER_AUDIO_RECORDER_ERROR_UNKNOWN:
                break;
            case StreamerConstants.KSY_STREAMER_CAMERA_ERROR_UNKNOWN:
            case StreamerConstants.KSY_STREAMER_CAMERA_ERROR_START_FAILED:
            case StreamerConstants.KSY_STREAMER_CAMERA_ERROR_EVICTED:
            case StreamerConstants.KSY_STREAMER_CAMERA_ERROR_SERVER_DIED:
                mStreamer.stopCameraPreview();
                break;
            case StreamerConstants.KSY_STREAMER_VIDEO_ENCODER_ERROR_UNSUPPORTED:
            case StreamerConstants.KSY_STREAMER_VIDEO_ENCODER_ERROR_UNKNOWN:
//                handleEncodeError();
            default:
//                reStreaming(what);
                break;
        }
    }

    private KSYStreamer.OnErrorListener mOnErrorListener = new KSYStreamer.OnErrorListener() {
        @Override
        public void onError(int what, int msg1, int msg2) {
            onStreamerError(what, msg1, msg2);
        }
    };


    private BaseStreamConfig getConfig() {
        BaseStreamConfig config = new BaseStreamConfig();
        config.mFrameRate = 15.0f;
        config.mVideoKBitrate = 800;
        config.mAudioKBitrate = 48;
        config.mFrameRate = 15;//Integer.parseInt(mFrameRateEditText.getText().toString());
        config.mVideoKBitrate = 800;//Integer.parseInt(mVideoBitRateEditText.getText().toString());
        config.mAudioKBitrate = 48;//Integer.parseInt(mAudioBitRateEditText.getText().toString());
        config.mCameraFacing = CameraCapture.FACING_FRONT;
        config.mTargetResolution = StreamerConstants.VIDEO_RESOLUTION_360P;
        config.mOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        config.mEncodeMethod = StreamerConstants.ENCODE_METHOD_HARDWARE;
        config.mAutoStart = false;//mAutoStartCheckBox.isChecked();
        config.mShowDebugInfo = true;//mShowDebugInfoCheckBox.isChecked();
        return config;
    }

    /***********************************
     * for sub move&switch
     ********************************/
    private float mSubTouchStartX;
    private float mSubTouchStartY;
    private float mLastRawX;
    private float mLastRawY;
    private float mLastX;
    private float mLastY;
    private float mSubMaxX = 0;   //小窗可移动的最大X轴距离
    private float mSubMaxY = 0;  //小窗可以移动的最大Y轴距离
    private boolean mIsSubMoved = false;  //小窗是否移动过了，如果移动过了，ACTION_UP时不触发大小窗内容切换
    private int SUB_TOUCH_MOVE_MARGIN = 30;  //触发移动的最小距离

    private CameraTouchHelper.OnTouchListener mSubScreenTouchListener = new CameraTouchHelper.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent event) {
            //获取相对屏幕的坐标，即以屏幕左上角为原点
            mLastRawX = event.getRawX();
            mLastRawY = event.getRawY();
            // 预览区域的大小
            int width = view.getWidth();
            int height = view.getHeight();
            //小窗的位置信息
            RectF subRect = mStreamer.getSubScreenRect();
            int left = (int) (subRect.left * width);
            int right = (int) (subRect.right * width);
            int top = (int) (subRect.top * height);
            int bottom = (int) (subRect.bottom * height);
            int subWidth = right - left;
            int subHeight = bottom - top;


            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    //只有在小屏区域才触发位置改变
                    if (isSubScreenArea(event.getX(), event.getY(), left, right, top, bottom)) {
                        //获取相对sub区域的坐标，即以sub左上角为原点
                        mSubTouchStartX = event.getX() - left;
                        mSubTouchStartY = event.getY() - top;
                        mLastX = event.getX();
                        mLastY = event.getY();
                    } else {
                        zhiboControlView.changeBottomBarState();
                    }
                    break;
                case MotionEvent.ACTION_MOVE:
                    int moveX = (int) Math.abs(event.getX() - mLastX);
                    int moveY = (int) Math.abs(event.getY() - mLastY);
                    if (mSubTouchStartX > 0f && mSubTouchStartY > 0f && (
                            (moveX > SUB_TOUCH_MOVE_MARGIN) ||
                                    (moveY > SUB_TOUCH_MOVE_MARGIN))) {
                        //触发移动
                        mIsSubMoved = true;
                        updateSubPosition(width, height, subWidth, subHeight);
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    //未移动并且在小窗区域，则触发大小窗切换
                    if (!mIsSubMoved && isSubScreenArea(event.getX(), event.getY(), left, right,
                            top, bottom)) {
                        mStreamer.switchMainScreen();
                    }

                    mIsSubMoved = false;
                    mSubTouchStartX = 0f;
                    mSubTouchStartY = 0f;
                    mLastX = 0f;
                    mLastY = 0f;
                    break;
            }

            return true;
        }
    };

    /**
     * 是否在小窗区域移动
     *
     * @param x      当前点击的相对小窗左上角的x坐标
     * @param y      当前点击的相对小窗左上角的y坐标
     * @param left   小窗左上角距离预览区域左上角的x轴距离
     * @param right  小窗右上角距离预览区域左上角的x轴距离
     * @param top    小窗左上角距离预览区域左上角的y轴距离
     * @param bottom 小窗右上角距离预览区域左上角的y轴距离
     * @return
     */
    private boolean isSubScreenArea(float x, float y, int left, int right, int top, int bottom) {
        if (!mStreamer.isRemoteConnected()) {
            return false;
        }

        if (x > left && x < right &&
                y > top && y < bottom) {
            return true;
        }

        return false;
    }

    /**
     * 触发移动小窗
     *
     * @param screenWidth 预览区域width
     * @param sceenHeight 预览区域height
     * @param subWidth    小窗区域width
     * @param subHeight   小窗区域height
     */
    private void updateSubPosition(int screenWidth, int sceenHeight, int subWidth, int subHeight) {
        mSubMaxX = screenWidth - subWidth;
        mSubMaxY = sceenHeight - subHeight;

        //更新浮动窗口位置参数
        float newX = (mLastRawX - mSubTouchStartX);
        float newY = (mLastRawY - mSubTouchStartY);

        //不能移出预览区域最左边和最上边
        if (newX < 0) {
            newX = 0;
        }

        if (newY < 0) {
            newY = 0;
        }

        //不能移出预览区域最右边和最下边
        if (newX > mSubMaxX) {
            newX = mSubMaxX;
        }

        if (newY > mSubMaxY) {
            newY = mSubMaxY;
        }
        //小窗的width和height不发生变化
        RectF subRect = mStreamer.getSubScreenRect();
        float width = subRect.width();
        float height = subRect.height();

        float left = newX / screenWidth;
        float top = newY / sceenHeight;

        mStreamer.setRTCSubScreenRect(left, top, width, height,
                KMCAgoraStreamer.SCALING_MODE_CENTER_CROP);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.ic_scale:
//                if (!isWebViewLarged) {
//                    bigWebView();
//                }else{
//                    smallWebView();
//                }
//                break;
            case R.id.accept_rtc:
                sendRtcOperation(true);
                break;
            case R.id.refuse_rtc:
                sendRtcOperation(false);
                break;
            case R.id.ic_video_scale:

                if (mZhiboScaleType == ZhiboScaleType.type_normal) {
                    mTopLayout.removeView(mZhiboContainer);
                    mLargeLayoutContainer.setVisibility(View.VISIBLE);
                    mLargeLayoutContainer.addView(mZhiboContainer, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                    mZhiboScaleType = ZhiboScaleType.type_zhibo_large;

                    mZhiboContainer.updateViewLayout(mPlayerView, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
//                    mZhiboContainer.updateViewLayout(mCameraPreviewView, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
//                    mZhiboContainer.updateViewLayout(mCameraHintView, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));

                } else {
                    mLargeLayoutContainer.removeView(mZhiboContainer);
                    mLargeLayoutContainer.setVisibility(View.GONE);
                    mTopLayout.addView(mZhiboContainer, 1, zhiboLayoutParams);
                    mZhiboScaleType = ZhiboScaleType.type_normal;

                    mZhiboContainer.updateViewLayout(mPlayerView, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
//                    mZhiboContainer.updateViewLayout(mCameraPreviewView, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
//                    mZhiboContainer.updateViewLayout(mCameraHintView, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
                }
                mPlayerView.setComeBackFromShare(true);
                mPlayerView.start();

                break;
            case R.id.ic_webview_scale:
                if (mZhiboScaleType == ZhiboScaleType.type_normal) {
                    mTopLayout.removeView(mWebViewContainer);
                    mLargeLayoutContainer.setVisibility(View.VISIBLE);
                    mLargeLayoutContainer.addView(mWebViewContainer, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                    mZhiboScaleType = ZhiboScaleType.type_web_large;
                } else {
                    mLargeLayoutContainer.removeView(mWebViewContainer);
                    mLargeLayoutContainer.setVisibility(View.GONE);
                    mTopLayout.addView(mWebViewContainer, 0, webLayoutParams);
                    mZhiboScaleType = ZhiboScaleType.type_normal;
                }
                break;

        }
    }

    private int mZhiboScaleType = ZhiboScaleType.type_normal;

    private interface ZhiboScaleType {
        int type_normal = 1001;
        int type_web_large = 1002;
        int type_zhibo_large = 1003;
    }

    public void sendRtcOperation(boolean accept) {
        if (accept) {
            Call<BaseResponse> call = MFPApplication.getInstance().getRestClient().sendMeetingInviteConfirm(mZhiboId, mRtcInviteModel.getData().getInvitekey());
            call.enqueue(new Callback<BaseResponse>() {
                @Override
                public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                    dismissProgressDialog();
                    mInviteLayout.setVisibility(View.GONE);

                }

                @Override
                public void onFailure(Call<BaseResponse> call, Throwable t) {
                    dismissProgressDialog();

                }
            });
            mInviteLayout.setVisibility(View.GONE);
        } else {
            Call<BaseResponse> call = MFPApplication.getInstance().getRestClient().sendMeetingInviteCancel(mZhiboId, mRtcInviteModel.getData().getInvitekey());
            call.enqueue(new Callback<BaseResponse>() {
                @Override
                public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                    dismissProgressDialog();
                    mInviteLayout.setVisibility(View.GONE);
                    zhiboControlView.setRtcBegin(false);
                }

                @Override
                public void onFailure(Call<BaseResponse> call, Throwable t) {
                    dismissProgressDialog();
                }
            });
        }

    }

    private boolean isWebViewLarged = false;

    private void bigWebView() {
//        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mMaterialContainerLayout.getLayoutParams();
//        layoutParams.height = getResources().getDimensionPixelSize(R.dimen.zhibo_web_height_big);
//        layoutParams.width = getResources().getDimensionPixelSize(R.dimen.zhibo_web_width_big);
//        mMaterialContainerLayout.setLayoutParams(layoutParams);
//        isWebViewLarged = true;
    }

    private void smallWebView() {
//        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mMaterialContainerLayout.getLayoutParams();
//        layoutParams.height = getResources().getDimensionPixelSize(R.dimen.zhibo_web_height_small);
//        layoutParams.width = getResources().getDimensionPixelSize(R.dimen.zhibo_web_width_small);
//        mMaterialContainerLayout.setLayoutParams(layoutParams);
//        isWebViewLarged = false;
    }

    //开始连麦
    public boolean startConference(String channelId) {
//        if (mIsCaling) {
//            return true;
//        }
        showProgressDialog("正在加入连麦 ...");
        startConferenceInternal(channelId);


        return true;
    }

    public void sendZhiboEventMsg(String zhiboOperType, String eventType, T data) {
        ZhiboAddImMsgRequest<T> zhiboAddImMsgRequest = new ZhiboAddImMsgRequest<>();
        zhiboAddImMsgRequest.setData(data);
        zhiboAddImMsgRequest.setId(mZhiboId);//zhiboBean.getId());
        zhiboAddImMsgRequest.setOpertype(zhiboOperType);
        zhiboAddImMsgRequest.setEventtype(eventType);
        Call<BaseResponse> call = MFPApplication.getInstance().getRestClient().sendZhiboEvent(zhiboAddImMsgRequest);
        call.enqueue(new Callback<BaseResponse>() {
            @Override
            public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                dismissProgressDialog();

            }

            @Override
            public void onFailure(Call<BaseResponse> call, Throwable t) {
                dismissProgressDialog();
            }
        });
    }

    //start streaming
    @Override
    public void startStream() {
        mStreamer.startStream();
    }


    private KSYStreamer.OnInfoListener mOnInfoListener = new KSYStreamer.OnInfoListener() {
        @Override
        public void onInfo(int what, int msg1, int msg2) {
            switch (what) {
                case StreamerConstants.KSY_STREAMER_CAMERA_INIT_DONE:
                    Log.d(TAG, "KSY_STREAMER_CAMERA_INIT_DONE");
                    setCameraAntiBanding50Hz();
                    if (mAutoStart) {
                        startStream();
                    }
                    break;
                case StreamerConstants.KSY_STREAMER_OPEN_STREAM_SUCCESS:
                    Log.d(TAG, "KSY_STREAMER_OPEN_STREAM_SUCCESS");
                    break;
                case StreamerConstants.KSY_STREAMER_OPEN_FILE_SUCCESS:
                    Log.d(TAG, "KSY_STREAMER_OPEN_FILE_SUCCESS");
                    break;
                case StreamerConstants.KSY_STREAMER_FRAME_SEND_SLOW:
                    Log.d(TAG, "KSY_STREAMER_FRAME_SEND_SLOW " + msg1 + "ms");
                    break;
                case StreamerConstants.KSY_STREAMER_EST_BW_RAISE:
                    Log.d(TAG, "BW raise to " + msg1 / 1000 + "kbps");
                    break;
                case StreamerConstants.KSY_STREAMER_EST_BW_DROP:
                    Log.d(TAG, "BW drop to " + msg1 / 1000 + "kpbs");
                    break;
                default:
                    Log.d(TAG, "OnInfo: " + what + " msg1: " + msg1 + " msg2: " + msg2);
                    break;
            }
        }
    };

    // Example to handle camera related operation
    private void setCameraAntiBanding50Hz() {
        Camera.Parameters parameters = mStreamer.getCameraCapture().getCameraParameters();
        if (parameters != null) {
            parameters.setAntibanding(Camera.Parameters.ANTIBANDING_50HZ);
            mStreamer.getCameraCapture().setCameraParameters(parameters);
        }
    }

    public void startConferenceInternal(String channelId) {

//        if (mIsLandscape) {
//            mStreamer.setRTCSubScreenRect(0.65f, 0.f, 0.3f, 0.35f, KMCAgoraStreamer
//                    .SCALING_MODE_CENTER_CROP);
//        } else {
//            mStreamer.setRTCSubScreenRect(0.65f, 0.f, 0.35f, 0.3f, KMCAgoraStreamer
//                    .SCALING_MODE_CENTER_CROP);
//        }

        mStreamer.setRTCSubScreenRect(0.6f, 0.05f, 0.2f, 0.6f, KMCAgoraStreamer
                .SCALING_MODE_FULL_FILL);
        //设置连麦时本地camera窗口位置尺寸
        mStreamer.setRTCMainScreenRect(0.f, 0.f, 1.0f, 1.0f,
                KMCAgoraStreamer.SCALING_MODE_CENTER_CROP);
        //设置主窗口为camera窗口
        mStreamer.setRTCMainScreen(KMCAgoraStreamer.RTC_MAIN_SCREEN_REMOTE);
        mStreamer.startRTC(channelId);
        mIsCaling = true;

    }

    public void stopConference2Server(String id, String channelId) {

        Call<BaseResponse> call = MFPApplication.getInstance().getRestClient().stopConference(id, channelId);
        call.enqueue(new Callback<BaseResponse>() {
            @Override
            public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                dismissProgressDialog();

            }

            @Override
            public void onFailure(Call<BaseResponse> call, Throwable t) {
                dismissProgressDialog();
            }
        });
    }

    @Override
    public boolean stopConference() {
        stopRtc();

        toast(getString(R.string.stop_conference), Toast.LENGTH_SHORT);
        mStreamer.onResume();
        startStream();
        return true;
    }

    private boolean stopRtc(){
        if (!mIsCaling) {
            return true;
        }

        stopConference2Server(mZhiboId, mRtcStartModel.getData().getChannel());

        changeUserStateRtc(false);

        mStreamer.stopRTC();
        mIsCaling = false;

//        mRtcRequest.setImageResource(R.mipmap.ic_rtc_begin);
//        mRtcRequest.postInvalidate();
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mStreamer != null) {
//            mStreamer.setDisplayPreview(mCameraPreviewView);
            mStreamer.onResume();
//            mCameraHintView.hideAll();
            startCameraPreviewWithPermCheck();
        }
        if(mIsActivityPaused){
            mPlayerView.runInForeground();
            onRefreshStream();
        }
        mIsActivityPaused = false;
    }


    private void startCameraPreviewWithPermCheck() {
        int cameraPerm = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
        int audioPerm = ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);
        if (cameraPerm != PackageManager.PERMISSION_GRANTED ||
                audioPerm != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                Log.e(TAG, "No CAMERA or AudioRecord permission, please check");
                Toast.makeText(this, "No CAMERA or AudioRecord permission, please check",
                        Toast.LENGTH_LONG).show();
            } else {
                String[] permissions = {Manifest.permission.CAMERA,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.READ_EXTERNAL_STORAGE};
                ActivityCompat.requestPermissions(this, permissions,
                        PERMISSION_REQUEST_CAMERA_AUDIOREC);
            }
        } else {
            mStreamer.startCameraPreview();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mIsActivityPaused = true;
        if (mPlayerView != null) {
            mPlayerView.runInBackground(true);
        }
        /**
         * Step 11: You must stop capture, stop conference, stop streaming when activity paused
         */

    }

    @Override
    protected void onStop() {
        super.onStop();

        if (mIsCaling && mStreamer != null) {
            stopRtc();
            stopPublishStreaming();
        } else {
            if (mPlayerView != null) {
                mPlayerView.pause();
                mPlayerView.stop();
//                mPlayerView.release();
            }
        }
    }

    @Override
    public void onFinish() {
        finish();

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[],
                                           @NonNull int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CAMERA_AUDIOREC: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    mStreamer.startCameraPreview();
                } else {
                    Log.e(TAG, "No CAMERA or AudioRecord permission");
                    Toast.makeText(this, "No CAMERA or AudioRecord permission",
                            Toast.LENGTH_LONG).show();
                }
                break;
            }
        }
    }


    private boolean stopPublishStreaming() {
        if (!mIsPublishStreamStarted) {
            return true;
        }
        mIsPublishStreamStarted = false;
        return false;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mGameView != null) {
            mGameView.loadUrl("about:blank");
        }
        if (mStreamer != null) {
            mStreamer.setOnLogEventListener(null);
            mStreamer.release();
        }
//        if (mPlayerView != null) {
//            mPlayerView.release();
//        }
        MyTIMMsgListener.removeITIMMsgReceivedCallback(this);
        NetChangeReceiver.removeNetCallback(this);
    }

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what != MESSAGE_ID_RECONNECTING || mIsActivityPaused || !mIsPublishStreamStarted) {
                return;
            }
            if (!NetWorkUtil.isNetworkAvailable(ZhiboBaseActivity.this)) {
                sendReconnectMessage();
                return;
            }
            Log.d(TAG, "do reconnecting ...");
        }
    };

    private void sendReconnectMessage() {
        toast("正在重连...", Toast.LENGTH_SHORT);
        mHandler.removeCallbacksAndMessages(null);
        mHandler.sendMessageDelayed(mHandler.obtainMessage(MESSAGE_ID_RECONNECTING), 500);
    }


    private IMediaPlayer.OnPreparedListener mOnPreparedListener = new IMediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(IMediaPlayer iMediaPlayer) {
            mPlayerView.setVideoScalingMode(KSYMediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
            mPlayerView.start();
            dismissProgressDialog();
        }
    };

    private IMediaPlayer.OnErrorListener mOnPlayerErrorListener = new IMediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(IMediaPlayer iMediaPlayer, int i, int i1) {
//            toast("播放器遇到错误，错误码:" + i, Toast.LENGTH_SHORT);
//            toast("播放器遇到错误");
//            videoPlayEnd();
            dismissProgressDialog();
//            finish();
            return false;
        }
    };

    private IMediaPlayer.OnInfoListener mOnPlayerInfoListener = new IMediaPlayer.OnInfoListener() {
        @Override
        public boolean onInfo(IMediaPlayer iMediaPlayer, int i, int i1) {
            switch (i) {
                case IMediaPlayer.MEDIA_INFO_BUFFERING_START:
                    showProgressDialog();
                    break;
                case IMediaPlayer.MEDIA_INFO_BUFFERING_END:
                    dismissProgressDialog();
                    break;
            }
            return false;
        }
    };


    private IMediaPlayer.OnCompletionListener mOnCompletionListener = new IMediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(IMediaPlayer iMediaPlayer) {
            toast("直播结束");
        }
    };


    private void videoPlayEnd() {
        if (mPlayerView != null) {
            mPlayerView.release();
        }
    }

    private boolean isShowNetWorkDialog = false;
    private long lastShowTime = 0l;

    @Override
    public void onNetWorkMethodChange(boolean isWifi) {
        if(lastShowTime != 0l){
            if(System.currentTimeMillis() - lastShowTime < 10000l){
                return;
            }
        }
        lastShowTime = System.currentTimeMillis();
        if (isShowNetWorkDialog == false && !isWifi) {
            isShowNetWorkDialog = true;
            new CommonChooseDialogFragment.CommonChooseDialogBuilder("继续观看", "停止观看", "您正在使用移动网络，继续观看会产生流量费用，建议您在Wi-Fi下观看。")
                    .setCommonChooseDialogClickListener(new CommonChooseDialogFragment.CommonChooseDialogClickListener() {
                        @Override
                        public void onConfirm() {
                            //停止拉流
                            isShowNetWorkDialog = false;
                            mPlayerView.pause();
                        }

                        @Override
                        public void onCancel() {
                            isShowNetWorkDialog = false;
//                            mPlayerView.setComeBackFromShare(true);
//                            mPlayerView.start();
                            onRefreshStream();
                            //继续观看
                        }
                    }).build(getSupportFragmentManager().beginTransaction());
        }else{
            onRefreshStream();
        }
    }

    @Override
    public void onNetWorkAvailableChange(boolean isAvailable) {
        if (!isAvailable) {
            toast("断网了");
        }
    }

}
